package com.xzzz.common.dblog;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.common.dblog.pojo.LogEntity;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DBAppender extends AppenderBase<LoggingEvent> {

    public DBAppender() {
        System.out.println(this.hashCode() + " > 创建DBAppender");
    }

    @Override
    protected void append(LoggingEvent logging) {
        LogEntity logEntity = buildLogEntity(logging);
        LogQueue.offer(logEntity);
    }

    private LogEntity buildLogEntity(LoggingEvent logging) {
        StackTraceElement[] cda = logging.getCallerData();
        LogEntity log = new LogEntity();
        log.setDatetime(DateUtil.date(logging.getTimeStamp()));
        log.setLevel(logging.getLevel().levelStr);
        log.setThread(logging.getThreadName());
        log.setTraceId(logging.getMDCPropertyMap().get("traceId"));
        log.setSpanId(logging.getMDCPropertyMap().get("spanId"));
        log.setClassName(logging.getLoggerName());
        log.setLine(cda != null && cda.length > 0 ? cda[0].getLineNumber() : 0);
        log.setMessage(logging.getFormattedMessage());
        if (log.getMessage().length() > 500) {
            log.setMessage(log.getMessage().substring(0, 500));
        }

        if (StrUtil.isBlank(log.getTraceId())) {
            log.setTraceId("");
        }

        if (StrUtil.isBlank(log.getSpanId())) {
            log.setSpanId("");
        }
        return log;
    }
}
